const http = require('http');

function makeRequest(options, data) {
  return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
      let body = '';
      res.on('data', (chunk) => {
        body += chunk;
      });
      res.on('end', () => {
        try {
          resolve(JSON.parse(body));
        } catch (e) {
          resolve(body);
        }
      });
    });
    
    req.on('error', reject);
    
    if (data) {
      req.write(JSON.stringify(data));
    }
    req.end();
  });
}

async function testRealNetworkAPI() {
  console.log('🎯 测试真实网络请求API');
  console.log('=' .repeat(50));
  console.log('');
  
  const testUrl = 'https://shop.tiktok.com/view/product/1731808168774042656?region=MY&local=en&source=product_detail';
  
  try {
    // 1. 测试处理商品链接（真实网络请求）
    console.log('📊 步骤1: 测试处理商品链接（真实网络请求）...');
    const processOptions = {
      hostname: 'localhost',
      port: 3000,
      path: '/api/products',
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    };
    
    const processResult = await makeRequest(processOptions, { url: testUrl });
    
    if (processResult.success) {
      console.log('   ✅ 商品处理成功');
      console.log('   📝 商品标题:', processResult.data.productName);
      console.log('   💰 价格:', processResult.data.priceUsd, 'USD');
      console.log('   🆔 商品ID:', processResult.data.id);
    } else {
      console.log('   ❌ 商品处理失败:', processResult.message);
      console.log('   💡 这可能是由于TikTok的反爬虫保护机制');
    }
    console.log('');
    
    // 2. 测试智能爬虫
    console.log('📊 步骤2: 测试智能爬虫...');
    const smartOptions = {
      hostname: 'localhost',
      port: 3000,
      path: '/api/products/test/smart',
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    };
    
    const smartResult = await makeRequest(smartOptions, { url: testUrl });
    
    if (smartResult.success) {
      console.log('   ✅ 智能爬虫测试成功');
      console.log('   📝 商品标题:', smartResult.data.title);
      console.log('   💰 价格:', smartResult.data.priceUsd, 'USD');
    } else {
      console.log('   ❌ 智能爬虫测试失败');
      console.log('   💡 这是正常现象，TikTok有强力的反爬虫保护');
    }
    console.log('');
    
    // 3. 获取商品列表
    console.log('📋 步骤3: 获取商品列表...');
    const listOptions = {
      hostname: 'localhost',
      port: 3000,
      path: '/api/products',
      method: 'GET'
    };
    
    const listResult = await makeRequest(listOptions);
    
    if (listResult.success) {
      console.log('   ✅ 商品列表获取成功');
      console.log('   📊 总商品数:', listResult.data.pagination.total);
      if (listResult.data.products.length > 0) {
        console.log('   📝 最新商品:', listResult.data.products[0].productName);
      }
    } else {
      console.log('   ❌ 商品列表获取失败');
    }
    console.log('');
    
    // 4. 获取统计信息
    console.log('📈 步骤4: 获取爬虫统计信息...');
    const statsOptions = {
      hostname: 'localhost',
      port: 3000,
      path: '/api/products/stats',
      method: 'GET'
    };
    
    const statsResult = await makeRequest(statsOptions);
    
    if (statsResult.success) {
      console.log('   ✅ 统计信息获取成功');
      console.log('   🤖 智能爬虫请求数:', statsResult.data.smartScraper.requestCount);
    } else {
      console.log('   ❌ 统计信息获取失败');
    }
    console.log('');
    
    console.log('🎉 API测试完成！');
    console.log('=' .repeat(50));
    console.log('');
    console.log('✨ 重要说明:');
    console.log('• API现在只使用真实网络请求');
    console.log('• 不再提供模拟数据选项');
    console.log('• 所有请求都会尝试获取真实的TikTok商品信息');
    console.log('• 如果爬虫失败，会返回错误而不是模拟数据');
    console.log('• 这确保了数据的真实性和准确性');
    
  } catch (error) {
    console.error('❌ 测试过程中出现错误:', error.message);
    console.log('');
    console.log('🔧 故障排除:');
    console.log('1. 确保服务器正在运行: npm run dev');
    console.log('2. 检查端口3000是否可用');
    console.log('3. 确认数据库连接正常');
  }
}

// 运行测试
testRealNetworkAPI();